#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QAction>
#include <QTextEdit>
#include <QToolBar>
#include <QTextCodec>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle(tr("文件窗口"));

    openNormal = new QAction("openFile", this);
    openNormal->setShortcuts(QKeySequence::Open);
    openNormal->setStatusTip(tr("Open an existing file"));
    connect(openNormal, &QAction::triggered, this, &MainWindow::normal);

    openSave = new QAction("saveFile", this);
    openSave->setShortcuts(QKeySequence::Save);
    openSave->setStatusTip(tr("Open an existing file"));
    connect(openSave, &QAction::triggered, this, &MainWindow::save);

    QToolBar *toolBar2 = addToolBar(tr("&File2"));
    toolBar2->addAction(openNormal);
    toolBar2->addAction(openSave);

    textEdit = new QTextEdit(this);
    setCentralWidget(textEdit);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::normal(){
    QString path = QFileDialog::getOpenFileName(this,
                                                tr("Open File"),
                                                ".",
                                                tr("Text Files(*.txt)"));
    if(!path.isEmpty()) {
        QFile file(path);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::warning(this, tr("Read File"),tr("Cannot open file:\n%1").arg(path));
            return;
        }
        QTextStream in(&file);
        in.setCodec(QTextCodec::codecForName("unicode"));
        textEdit->setText(in.readAll());
        file.close();
    } else {
        QMessageBox::warning(this, tr("Path"),tr("You did not select any file."));
    }
}

void MainWindow::save(){
    QString path = QFileDialog::getSaveFileName(this,tr("Open File"),".",tr("Text Files(*.txt)"));
    if(!path.isEmpty()) {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::warning(this, tr("Write File"),tr("Cannot open file:\n%1").arg(path));
            return;
        }
        QTextStream out(&file);
        out << textEdit->toPlainText();
        file.close();
    } else {
        QMessageBox::warning(this, tr("Path"),tr("You did not select any file."));
    }
}
